﻿using DefCore;
using DefCore.Interfaces;
using DefCore.Tools;
using DefCore.Mapping;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Defender.Tools
{
    [Serializable]
    public sealed class DefenderLevelFile : IAssignable<LevelBase>
    {
        //Fields
        public int[,] WorldMapMatrix;
        public RuleSet WorldRuleSet;

        //ctor
        public DefenderLevelFile()
        {

        }

        //Methods
        public void CreateSaveFrom(LevelBase obj)
        {
            this.WorldMapMatrix = ConversionTools.ConvertCellsToInts(obj.GameCellMap);
            this.WorldRuleSet = RuleSet.Current;
        }
        public void CreateFromLoad(LevelBase obj)
        {
            obj.GameCellMap = new CellMap(ConversionTools.ConvertIntsToCells(this.WorldMapMatrix));
            RuleSet.Current = this.WorldRuleSet;
        }

        private void Assign(DefenderLevelFile temp)
        {
            this.WorldMapMatrix = temp.WorldMapMatrix;
            this.WorldRuleSet = temp.WorldRuleSet;
        }

        public void Save(string file)
        {
            using (FileStream fs = File.Open(string.Format(@"{0}\data\{1}.dlf", Objects.GameObject.Content.RootDirectory, file), FileMode.OpenOrCreate))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, this);
            }
        }
        public void Load(string file)
        {
            using (FileStream fs = File.Open(string.Format(@"{0}\data\{1}.dlf", Objects.GameObject.Content.RootDirectory, file), FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                Assign((DefenderLevelFile)bf.Deserialize(fs));
            }
        }
    }
}
